package com.qf.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

public class SpringEnvironmentListener implements GenericApplicationListener {

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return eventType.getRawClass() == ApplicationEnvironmentPreparedEvent.class;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("SpringBoot环境初始化完成！");
        //强制转换事件类型
        ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event;
        //获得SpringBoot初始化成功的环境对象
        ConfigurableEnvironment environment = environmentPreparedEvent.getEnvironment();
        //根据环境对象获取微服务名称
        String appName = environment.getProperty("spring.application.name");
//        System.out.println("微服务名称：" + appName);

        MDC.put("logName", appName);
        MDC.put("logPath", appName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
